// ignore_for_file: non_constant_identifier_names, unnecessary_brace_in_string_interps, depend_on_referenced_packages, library_prefixes

import 'dart:convert';
import 'package:aitao_flutter/utils/sp_utils.dart';
import 'package:crypto/crypto.dart';
import 'dart:math';
import "dart:io";
import "package:dio/dio.dart";
import 'package:flutter/material.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart' as wxAssets;

String ossAccessKeyId = SpUtil.getAccessKeyId();
// oss设置的bucket的名字
String bucket = SpUtil.getOssBucket();
String ossAccessKeySecret = SpUtil.getAccessKeySecret();
String ossSecurityToken = SpUtil.getSecurityToken();

// 发送请求的url,
String url = 'https://$bucket.oss-cn-hangzhou.aliyuncs.com';

// 过期时间
String expiration = SpUtil.getExpiration();

// String expiration = '2050-01-01T12:00:00.000Z';

class OssUtil {
  //验证文本域
  static final String _policyText =
      '{"expiration": "$expiration","conditions": [["content-length-range", 0, 1048576000]]}'; //UTC时间+8=北京时间

  //进行utf8编码
  static final List<int> _policyText_utf8 = utf8.encode(_policyText);
  //进行base64编码
  static String policy = base64.encode(_policyText_utf8);

  //再次进行utf8编码
  static final List<int> _policy_utf8 = utf8.encode(policy);

  // 工厂模式
  factory OssUtil() => _getInstance();

  static OssUtil get instance => _getInstance();
  static OssUtil? _instance;

  OssUtil._internal();

  static OssUtil _getInstance() {
    _instance ??= OssUtil._internal();
    return _instance!;
  }

  /// 获取signature签名参数
  String getSignature(String accessKeySecret) {
    //进行utf8 编码
    List<int> AccessKeySecretUtf8 = utf8.encode(accessKeySecret);
    //通过hmac,使用sha1进行加密
    List<int> signaturePre =
        Hmac(sha1, AccessKeySecretUtf8).convert(_policy_utf8).bytes;
    //最后一步，将上述所得进行base64 编码
    String signature = base64.encode(signaturePre);
    return signature;
  }

  // ignore: slash_for_doc_comments
  /**
   * 生成上传上传图片的名称 ,获得的格式:photo/20171027175940_oCiobK
   * 可以定义上传的路径uploadPath(Oss中保存文件夹的名称)
   * @param uploadPath 上传的路径 如：/photo
   * @return photo/20171027175940_oCiobK
   */
  String getImageUploadName(String uploadPath, String filePath) {
    String imageMame = "";
    var timestamp = DateTime.now().millisecondsSinceEpoch;
    imageMame = "${timestamp}_${getRandom(6)}";
    if (uploadPath.isNotEmpty) {
      imageMame = "$uploadPath/$imageMame";
    }
    var imageType =
        filePath.substring(filePath.lastIndexOf("."), filePath.length);
    return '$imageMame$imageType';
  }

  String getImageName(String filePath) {
    String imageMame = "";
    var timestamp = DateTime.now().millisecondsSinceEpoch;
    // ignore: prefer_interpolation_to_compose_strings
    imageMame = 'app' + timestamp.toString() + "_" + getRandom(6);
    var imageType =
        filePath.substring(filePath.lastIndexOf("."), filePath.length);
    return '$imageMame$imageType';
  }

  /// 生成固定长度的随机字符串
  static String getRandom(int num) {
    String alphabet = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM';
    String left = '';
    for (var i = 0; i < num; i++) {
//    right = right + (min + (Random().nextInt(max - min))).toString();
      left = left + alphabet[Random().nextInt(alphabet.length)];
    }
    return left;
  }

  /// 根据图片本地路径获取图片名称
  ///
  String? getImageNameByPath(String filePath) {
    // ignore: null_aware_before_operator
    return filePath.substring(filePath.lastIndexOf("/") + 1, filePath.length);
  }

  /// 获取日期
  ///
  static String getDate() {
    DateTime now = DateTime.now();
    return "${now.year}${now.month}${now.day}";
  }
}

class UploadOss {
  /*
   * @params file 要上传的文件对象
   * @params rootDir 阿里云oss设置的根目录文件夹名字
   * @param fileType 文件类型例如jpg,mp4等
   * @param callback 回调函数我这里用于传cancelToken，方便后期关闭请求
   * @param onSendProgress 上传的进度事件
   */
  static Future<String> upload(File file,
      {String rootDir = "uploads", required String fileType}) async {
    // 生成oss的路径和文件名我这里目前设置的是moment/20201229/test.mp4
    //print('压缩前图片文件大小:' + file.lengthSync().toString());

    String pathName =
        "$rootDir/${OssUtil.getDate()}/${OssUtil.getRandom(12)}.${fileType}";
    // 请求参数的form对象
    FormData formdata = FormData.fromMap({
      //文件名，随意
      'Filename': OssUtil.instance.getImageName(file.path),
      //"可以填写文件夹名（对应于oss服务中的文件夹）/" + fileName
      'key': pathName, //上传后的文件名
      'policy': OssUtil.policy,
      //Bucket 拥有者的AccessKeyId。
      'OSSAccessKeyId': ossAccessKeyId,
      //让服务端返回200，不然，默认会返回204
      'success_action_status': '200',
      'signature': OssUtil.instance.getSignature(ossAccessKeySecret),
      'x-oss-security-token': ossSecurityToken,
      'file': MultipartFile.fromFileSync(file.path, filename: 'test'),
      //必须放在参数最后
    });
    Dio dio = Dio();
    dio.options.responseType = ResponseType.plain;
    // dio.options.contentType = ContentType.parse('multipart/form-data') as String?;
    try {
      debugPrint('请求地址url:${url}');
      // 发送请求
      await dio.post(url, data: formdata);
      // 成功后返回文件访问路径
      debugPrint('成功后返回文件访问路径:${pathName}');
      // return "${url}/$pathName";
      return "/$pathName";
    } on DioException catch (er) {
      debugPrint('上传失败:${er.toString()}');
      return '';
    }
  }

  /// 上传多张图片
  static Future<String> uploadImages(List<wxAssets.AssetEntity> files,
      {String rootDir = "uploads"}) async {
    if (files.isEmpty) return '';

    var finishResult = await fetchData(rootDir, files);
    if (finishResult == '') throw '图片上传失败';
    debugPrint('全部图片上传完成:${finishResult}');
    return finishResult;
  }

  static Future<String> fetchData(
      String rootDir, List<wxAssets.AssetEntity> files) async {
    // 发起第一个异步请求

    String finishResult = '';
    for (var i = 0; i < files.length; i++) {
      File? imgFile = await files[i].file;
      String pathName =
          "$rootDir/${OssUtil.getDate()}/${OssUtil.getRandom(12)}.png";
      FormData formdata = FormData.fromMap({
        //文件名，随意
        'Filename': OssUtil.instance.getImageName(imgFile!.path),
        //"可以填写文件夹名（对应于oss服务中的文件夹）/" + fileName
        'key': pathName, //上传后的文件名
        'policy': OssUtil.policy,
        //Bucket 拥有者的AccessKeyId。
        'OSSAccessKeyId': ossAccessKeyId,
        //让服务端返回200，不然，默认会返回204
        'success_action_status': '200',
        'signature': OssUtil.instance.getSignature(ossAccessKeySecret),
        'x-oss-security-token': ossSecurityToken,
        'file': MultipartFile.fromFileSync(imgFile.path, filename: 'test'),
        //必须放在参数最后
      });
      Dio dio = Dio();
      dio.options.responseType = ResponseType.plain;
      // dio.options.contentType = ContentType.parse('multipart/form-data') as String?;
      try {
        // debugPrint('请求地址url:${url}');
        // 发送请求
        await dio.post(url, data: formdata);
        // return "/$pathName";
        if (i == files.length - 1) {
          finishResult += '/$pathName';
          debugPrint('成功后返回文件访问路径:${finishResult}');

          return finishResult;
        } else {
          finishResult += '/$pathName,';
        }
      } on DioException catch (er) {
        debugPrint('上传失败:${er.toString()}');
        return '';
      }
    }
    return '';
  }
}
